package cn.hellochaos.generator.config;

import cn.hellochaos.generator.interceptor.LoginInterceptor;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebAppConfig implements WebMvcConfigurer {
    //read imgpath from config file
    @Value("${spring.resources.static-locations}")
    private String mImagesPath;

//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        registry.addInterceptor(new LoginInterceptor())
//                //拦截所有路径
//                .addPathPatterns("/**")
//                //除了登录路径
//                .excludePathPatterns("/fishery/api/v1/user/login")
//                //注册路径
//                .excludePathPatterns("/fishery/api/v1/user/register");
//    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        if (mImagesPath.equals("") || mImagesPath.equals("${spring.resources.static-locations}"))
        {
            //检查路径是否有jar
            String imagesPath = WebAppConfig.class.getClassLoader().getResource("").getPath();
            //获取项目的路径，并且去掉jar
            if (imagesPath.indexOf(".jar") > 0)
            {
                imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
            }
            else if (imagesPath.indexOf("classes") > 0)
            {
                imagesPath = "file:" + imagesPath.substring(0, imagesPath.indexOf("classes"));
            }
            imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/")) + "/images/";
            mImagesPath = imagesPath;
        }
        LoggerFactory.getLogger(WebAppConfig.class).info("imagesPath=" + mImagesPath);
        registry.addResourceHandler("/images/**").addResourceLocations(mImagesPath);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 直接加@CrossOrigin,跨域问题并没有解决因为这个注解默认origin为*在axios中不允许
        // /*表示 /a可以，/a/b不行， /**表示 /a/b/c/d都可以
        /*
        本地测试环境,前端接口的地址
         */
//        registry.addMapping("/**").allowedOrigins("http://localhost"+":8080").allowCredentials(true);

        /*
        远程服务器环境
         */
        registry.addMapping("/**").allowedOrigins("http://120.77.156.205"+":9506","http://localhost"+":8080").allowCredentials(true);
    }
}
